import os

from django.http import HttpResponse, Http404, StreamingHttpResponse, FileResponse
from django.shortcuts import render


# Create your views here.


def index(request):
    html = """
    <h1>Hello D_FBV视图</h1>
    """
    return HttpResponse(html)


def g_render(request):
    value = 'Hello D_FBV视图'
    context = {'name': "艾则麦提", 'age': 23, 'gender': "男", 'hobby': ['篮球', '足球', '羽毛球']}

    return render(request, 'index.html', locals())


# 下载功能
def download1(request):
    # 下载文件
    file_name = 'C:/Users/lenovo/Desktop/3.喀什市2024年面向社会公开招聘社区工作者报名表.doc'
    try:
        response = HttpResponse(open(file_name, 'rb'))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="%s"' % file_name.split('/')[-1]
        return response
    except Exception as e:
        return Http404('文件不存在')


def download2(request):
    file_name = 'C:/Users/lenovo/Desktop/艾则麦提·艾力.pdf'
    try:
        response = StreamingHttpResponse(open(file_name, 'rb'))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="%s"' % file_name.split('/')[-1]
        return response
    except Exception as e:
        return Http404('文件不存在')


def download3(request):
    file_name = 'C:/Users/lenovo/Desktop/3.喀什市2024年面向社会公开招聘社区工作者报名表.doc'
    try:
        f = open(file_name, 'rb')
        response = FileResponse(f, as_attachment=True, filename=file_name.split('/')[-1])
        return response
    except Exception as e:
        return Http404('文件不存在')


def download4(request):
    return render(request, 'download.html')


def g_request(request):
    if request.method == 'GET':
        # 类的使用
        print(request.is_secure())  # 判断是否是https请求
        print(request.get_host())  # 获取请求的域名
        print(request.get_full_path())  # 获取请求的完整路径
        # 属性的使用
        print(request.path)  # 获取请求的完整路径
        print(request.scheme)  # 获取请求协议
        print(request.method)  # 获取请求方法
        print(request.GET)  # 获取get请求参数
        print(request.COOKIES)  # 获取cookie
        print(request.content_type)  # 获取请求内容类型
        print(request.content_params)  # 获取请求内容参数
        return render(request, 'requests.html')
    elif request.method == 'POST':
        # 类的使用
        print(request.is_secure())  # 判断是否是https请求
        print(request.get_host())  # 获取请求的域名
        print(request.get_full_path())  # 获取请求的完整路径
        # 属性的使用
        print(request.path)  # 获取请求的完整路径
        print(request.scheme)  # 获取请求协议
        print(request.method)  # 获取请求方法
        print(request.POST)  # 获取get请求参数
        print(request.COOKIES)  # 获取cookie
        print(request.content_type)  # 获取请求内容类型
        print(request.content_params)  # 获取请求内容参数
        return render(request, 'requests.html')
    else:
        return HttpResponse('请求方式错误')


# 上传文件
def upload(request):
    if request.method == 'POST':
        print(request.FILES)
        Myfile = request.FILES.get('myfile')
        if Myfile:
            print(Myfile.name)  # 获取文件名
            print(Myfile.size)  # 获取文件大小
            print(Myfile.content_type)  # 获取文件类型

            # 确保FILE目录存在
            file_dir = "FILE"
            if not os.path.exists(file_dir):
                os.makedirs(file_dir)

            # 完整的文件路径
            file_url = os.path.join(file_dir, Myfile.name)

            try:
                with open(file_url, 'wb') as f:
                    for chunk in Myfile.chunks():  # 分块写入文件
                        f.write(chunk)
                return HttpResponse('上传成功')
            except Exception as e:
                print(f"文件上传失败: {e}")  # 打印错误信息到服务器控制台
                return HttpResponse(f'上传失败: {e}')
        else:
            return HttpResponse('上传失败，没有文件被上传')
    elif request.method == 'GET':
        return render(request, 'upload.html')